package com.qingke.test;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.omg.CORBA.portable.InputStream;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Connection conn;
	private PreparedStatement stat;
	private ResultSet  rs;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		Dao dao =new Dao();
		conn=dao.getConnection();
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		if (stat != null) {
			try {
				stat.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String sql="select * from student_login where username=? and password=?";
		HttpSession session =request.getSession();
		String checkcode1=request.getParameter("code");
		String checkcode2 =(String) request.getSession().getAttribute("checkcode");
		
		try {
			
			stat =conn.prepareStatement(sql);
			stat.setString(1, username);
			stat.setString(2, password);
			
			rs=stat.executeQuery();
			if(rs.next()&&checkcode1.equalsIgnoreCase(checkcode2)){
				
				session.setAttribute("username", username);
				session.setAttribute("password", password);
				response.sendRedirect("success.jsp");
				
			}else{
				
				throw new NullPointerException();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
